package designpatterns.singletonpattern;

import java.util.concurrent.locks.ReentrantLock;

public class LazyInitialization {
    private static LazyInitialization instance;
    private LazyInitialization(){
    }
    /**
     //     * 线程安全方案四
     //     * @return
     //     */
    private static final ReentrantLock lock = new ReentrantLock();
    public static LazyInitialization getInstance(){
        if(instance == null){
            //将 lock.lock() 移出 try 块，避免在获取锁失败时仍执行 unlock()
            lock.lock();
            try {
                if(instance == null){
                    instance = new LazyInitialization();
                }
            } finally {
                lock.unlock();
            }
        }
        return instance;
    }

//    /**
//     * 线程安全方案三
//     */
//    private static class SingletonHolder {
//        // 这行代码不会在类加载时立即执行
//        private static final LazyInitialization INSTANCE = new LazyInitialization();
//    }
//
//    public static LazyInitialization getInstance() {
//        // 只有调用这个方法时，SingletonHolder 才会被加载
//        return SingletonHolder.INSTANCE;
//    }


//    /**
//     * 线程安全方案二
//     * @return
//     */
//    public static LazyInitialization getInstance(){
//        if(instance == null){
//            synchronized (LazyInitialization.class){
//                if(instance == null){
//                    instance = new LazyInitialization();
//                }
//            }
//        }
//        return instance;
//    }

//    /**
//     * 线程安全方案一
//     * @return
//     */
//    public static synchronized LazyInitialization getInstance(){
//        if(instance == null){
//            instance = new LazyInitialization();
//        }
//        return instance;
//    }

//    /**
//     * 线程不安全
//     * @return 对象
//     */
//    public static LazyInitialization getInstance(){
//        if(instance == null){
//            instance = new LazyInitialization();
//        }
//        return instance;
//    }
}
